import os
import sys
import rtconfig

print("开始构建...")

if os.getenv('RTT_ROOT'):
    RTT_ROOT = os.getenv('RTT_ROOT')
else:
    RTT_ROOT = os.path.normpath(os.getcwd() + '/../../../..')
    print('RTT_ROOT: ' + RTT_ROOT)

# FMT path
FMU_ROOT = os.path.normpath(os.getcwd() + '/../../../../../..')
FMU_ROOT = os.path.join(FMU_ROOT, 'fmt')
print('FMU_ROOT: ' + FMU_ROOT)

fmt_tools = os.path.join(os.getcwd(), 'fmt_tools')
sys.path.append(fmt_tools)
print('FMT tools path: ' + fmt_tools)

sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
try:
    from building import *
except:
    print('Cannot found RT-Thread root directory, please check RTT_ROOT')
    print(RTT_ROOT)
    exit(-1)

# ===== Set the target =====
TARGET = 'build/fmt_' + rtconfig.BOARD + '.' + rtconfig.TARGET_EXT
print('Target = ' + TARGET)

print("----------------------------------------")

# ===== Add option to SCons =====
AddOption('--vehicle',
                dest = 'vehicle',
                type = 'string',
                default = 'Multicopter',
                help = 'Specify the vehicle type')

AddOption('--airframe', 
                dest='airframe', 
                type='int', 
                nargs=1, 
                default = 1, 
                action='store',
                help='Specify the airframe value')

'''
    创建一个 Environment 对象，指定要使用的工具为 'mingw'
    'mingw' 是一个用于 Windows 的 GCC 编译器集合
    设置汇编器\编译器\链接器\静态库打包工具(archiver)等, 以及对应的参数
    使用 env 来构建目标文件、库或可执行文件
'''
DefaultEnvironment(tools=[])
env = Environment(tools = ['mingw'],
    AS = rtconfig.AS, ASFLAGS = rtconfig.AFLAGS,
    CC = rtconfig.CC, CCFLAGS = rtconfig.CFLAGS,
    AR = rtconfig.AR, ARFLAGS = '-rc',
    CXX = rtconfig.CXX, CXXFLAGS = rtconfig.CXXFLAGS,
    LINK = rtconfig.LINK, LINKFLAGS = rtconfig.LFLAGS, LIBS = rtconfig.LLIBS)

# set VEHICLE_TYPE macro for low-level usage
env.Append(CPPDEFINES = [('VEHICLE_TYPE', GetOption('vehicle'))])
env.Append(CPPDEFINES = [('AIRFRAME', GetOption('airframe'))])

# Add sys execute PATH to env PATH
env.PrependENVPath('PATH', os.getenv('PATH'))
env.PrependENVPath('PATH', rtconfig.EXEC_PATH)

if rtconfig.PLATFORM in ['iccarm']:
    env.Replace(CCCOM = ['$CC $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS -o $TARGET $SOURCES'])
    env.Replace(ARFLAGS = [''])
    env.Replace(LINKCOM = env["LINKCOM"] + ' --map rtthread.map')

# 设置或导出系统中的环境变量，使其在子进程sconscript中也可用.
Export('RTT_ROOT')
Export('rtconfig')

SDK_ROOT = os.path.abspath('./')
SCONS_ROOT = os.path.abspath('./')

if os.path.exists(SDK_ROOT + '/libraries'):
    libraries_path_prefix = SDK_ROOT + '/libraries'
else:
    libraries_path_prefix = os.path.dirname(SDK_ROOT) + '/libraries'

SDK_LIB = libraries_path_prefix

Export('SDK_LIB')
Export('SCONS_ROOT')

# prepare building environment
objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False)

qx_library = 'libs'
rtconfig.BSP_LIBRARY_TYPE = qx_library

# include libraries
objs.extend(SConscript(os.path.join(libraries_path_prefix, qx_library, 'SConscript')))

# include drivers
objs.extend(SConscript(os.path.join(libraries_path_prefix, 'drivers', 'SConscript')))

# (Dir('#'): 返回当前SConscript文件的目录,将这个Dir对象转换成一个字符串。
# 通常，这个字符串会是目录的绝对路径
# 遍历目录列表并构建每个目录中的 SConscript 文件
cwd = str(Dir('#'))
list = os.listdir(FMU_ROOT)
vdir = 'build/fmt'
for d in list:
    path = os.path.join(FMU_ROOT, d)
    print(path)
    if os.path.isfile(os.path.join(path, 'SConscript')):
        print(os.path.join(path, 'SConscript'))
        objs.extend(SConscript(os.path.join(path, 'SConscript'),
                    variant_dir=vdir + '/' + d, duplicate=0))

# make a building
print('------------------------------------------------------')
print('Building...')
DoBuilding(TARGET, objs)
